<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="900px" :title="`${drawerProps.title}`">
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="明细列表"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :is-show-search="false"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <!-- <el-button v-auth="'add'" type="primary" @click="openDrawer('新增')"> 新增用户 </el-button> -->
          <!-- <el-button v-auth="'batchAdd'" type="primary" :icon="Upload" plain @click="batchAdd"> 批量添加用户 </el-button>
              <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="downloadFile"> 导出用户数据 </el-button> -->
          <!-- <el-button type="primary" plain @click="toDetail"> To 子集详情页面 </el-button> -->
          <!-- <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
                批量删除用户
              </el-button> -->
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- usernameHeader -->
        <template #status="scope">
          <el-button type="primary">
            {{ statusList[scope.row.status] }}
          </el-button>
        </template>
      </ProTable>
    </div>
  </el-drawer>
</template>

<script setup lang="tsx" name="detail">
import { ref, reactive, getCurrentInstance, onMounted } from "vue"; // onMounted
// import { useRouter } from "vue-router";
import { User, Dict } from "@/api/interface";
// import { useHandleData } from "@/hooks/useHandleData";
// import { useDownload } from "@/hooks/useDownload";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
//import { ElMessage } from "element-plus"; // ElMessageBox
import ProTable from "@/components/ProTable/index.vue";
// import { genderType } from "@/utils/serviceDict"; // userStatus
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
// import { CirclePlus, Delete, EditPen, View, Refresh } from "@element-plus/icons-vue"; // Download, Upload,
import { getDict, pageAllIntegralDetail } from "@/api/modules/sys"; // exportUserInfo,BatchAddUser
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
const userStatus: Dict.ResDictList[] = ref();
const statusList = ref({});
const integralDetail = ref([]);
const drawerVisible = ref(false);

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  integralDetail: Dict.ResDictList[];
  isAdd: boolean;
}
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {
    roleId: []
  },
  integralDetail: [],
  isAdd: false
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  params.row.roleId = params.row.roleId || [];
  drawerProps.value = params;
  drawerVisible.value = true;
};

defineExpose({
  acceptParams
});

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
// 获取字典数据
const getDicList = async (params: Dict.ResDictList) => {
  const { data } = await getDict(params);
  return data || [];
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  data.records =
    (data.records &&
      data.records.map(item => {
        const obj = userStatus.value.find(itm => itm.id === item.typeId);
        item.typeName = obj.name;
        return item;
      })) ||
    [];
  console.log(data.records);
  return {
    list: data.records,
    total: Number(data.total),
    pageNum: Number(data.current),
    pageSize: Number(data.size)
  };
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  // let newParams = JSON.parse(JSON.stringify(params));
  // newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  // newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  // 获取用户状态
  // 处理字段文字
  userStatus.value = await getDicList({ parentId: dict.integralId });
  // newParams
  const newParams = {
    currentPage: params.pageNum,
    userId: drawerProps.value.row.id
  };
  return pageAllIntegralDetail(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
//const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
//   return <el-button type="primary">{scope.column.label}</el-button>;
// };

// 表格配置项
const columns: ColumnProps<User.ResUserList>[] = [
  // { type: "selection", fixed: "left", width: 80 },
  // { type: "index", label: "#", width: 80 },
  // { type: "expand", label: "Expand", width: 100 },
  {
    prop: "id",
    label: "ID"
  },
  {
    prop: "currentIntegral",
    label: "当前积分"
  },
  // { prop: "status", label: "状态" },
  // {
  //   prop: "sex",
  //   label: "性别",
  //   // 字典数据
  //   // enum: genderType,
  //   // 字典请求不带参数
  //   enum: genderType
  //   // 字典请求携带参数
  //   // enum: () => getUserGender({ id: 1 }),
  // },
  // { prop: "mobile", label: "手机号" },
  { prop: "detail", label: "变更积分" },
  { prop: "typeName", label: "变更理由" },
  {
    prop: "gmtCreate",
    label: "创建时间",
    width: 180
  }
  // {
  //   prop: "gmtModified",
  //   label: "修改时间",
  //   width: 180,
  //   search: {
  //     el: "date-picker",
  //     span: 2,
  //     props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
  //     defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
  //   }
  // }
];
onMounted(async () => {
  integralDetail.value = await getDicList({ parentId: dict.integralId });
});
</script>
